package com.dkd.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicBoolean;

public class Refreshable {

    protected  AtomicBoolean refresh = new AtomicBoolean(false);
    public void register() {
        SpringBootRegister.registerBean(this.getClass().getCanonicalName(),this);
    }

    public synchronized void refresh(ApplicationContext applicationContext) {
        if (!refresh.get()) {
            for (Field declaredField : this.getClass().getDeclaredFields()) {
                if (declaredField.isAnnotationPresent(Autowired.class)) {
                    declaredField.setAccessible(true);
                    try {
                        declaredField.set(this, applicationContext.getBean(declaredField.getType()));
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            refresh.set(true);
        }

    }
}
